package com.sanrenzu.everybodytv.ui.recommend_live;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.BackgroundColorSpan;
import android.text.style.ImageSpan;
import android.view.Display;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sanrenzu.everybodytv.R;
import com.sanrenzu.everybodytv.bean.sms.live.ZhiBoBean;
import com.sanrenzu.everybodytv.utils.ToastUtils;
import com.sanrenzu.everybodytv.widget.GlideRoundTransform;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;
import master.flame.danmaku.controller.IDanmakuView;
import master.flame.danmaku.danmaku.loader.ILoader;
import master.flame.danmaku.danmaku.loader.IllegalDataException;
import master.flame.danmaku.danmaku.loader.android.DanmakuLoaderFactory;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.model.android.SpannedCacheStuffer;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.danmaku.parser.IDataSource;
import master.flame.danmaku.danmaku.parser.android.BiliDanmukuParser;
import master.flame.danmaku.danmaku.util.IOUtils;

public class VideoViewActivity extends AppCompatActivity implements VideoViewContract.View {
    //VideoView的播放窗口
    @BindView(R.id.videoView)
    VideoView videoView_videoPlay;
    //头像
    @BindView(R.id.imageView_viewView_touxiang)
    ImageView imageViewViewViewTouxiang;
    //名字
    @BindView(R.id.textView_videoView_name)
    TextView textViewVideoViewName;
    //介绍
    @BindView(R.id.textView_videoView_jieshao)
    TextView textViewVideoViewJieshao;
    //关注按钮
    @BindView(R.id.radioButton_videoView_guanzhu)
    CheckBox radioButtonVideoViewGuanzhu;
    //tabLayout
    @BindView(R.id.tabLayout_videoView)
    TableLayout tabLayoutVideoView;
    //帧布局占位
    @BindView(R.id.frameLayout_videoView_content)
    FrameLayout frameLayoutVideoViewContent;
    //对话输入聊天框
    @BindView(R.id.editText_videoView)
    EditText editTextVideoView;
    //礼物按钮
    @BindView(R.id.imageView_videoView_liwu)
    ImageView imageViewVideoViewLiwu;
    //返回按钮
    @BindView(R.id.imageView_viewView_back)
    ImageView imageViewViewViewBack;
    //全屏按钮
    @BindView(R.id.imageView_viewView_full)
    ImageView imageViewViewViewFull;
    //没全屏的布局上边的
    @BindView(R.id.relativeLayout_videoView_vertical1)
    RelativeLayout relativeLayoutVideoViewVertical1;
    //下边的
    @BindView(R.id.relativeLayout_videoView_vertical2)
    RelativeLayout relativeLayoutVideoViewVertical2;
    @BindView(R.id.textView_videoView_guanzhu)
    TextView textViewVideoViewGuanzhu;
    private Context context = this;
    private MediaController controller = null;
    //手势监听
    private GestureDetectorCompat gesture;
    //获取当前声音
    private int customVolume = -1;
    //获取最大声音
    private int maxVolume = 0;
    //获取音频管理器
    private AudioManager audioManager = null;
    //获取当前亮度
    private float mBrightness = -1f;
    //声明uid
    private String uid;
    //声明P层对象
    private VdeoViewPresenter presenter;
    //声明网址
    private String url;
    //弹幕的对象初始
    private BaseDanmakuParser mParser;
    //解析器对象
    private IDanmakuView mDanmakuView;
    //弹幕的对象初始
    private DanmakuContext mContext;
    private Unbinder bind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_view);
        bind = ButterKnife.bind(this);
        //调用初始化弹幕的方法
        if(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            //隐藏标题栏
            supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
            //隐藏状态栏这两个必须放到setContentView上边
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        initView();
        initData();
        initOther();
    }

    //初始化弹幕控件方法
    private void initView() {
        //实例化
        mDanmakuView = (IDanmakuView) findViewById(R.id.sv_danmaku);
        mContext = DanmakuContext.create();
        // 设置弹幕的最大显示行数
        HashMap<Integer, Integer> maxLinesPair = new HashMap<Integer, Integer>();
        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL, 3); // 滚动弹幕最大显示3行
        // 设置是否禁止重叠
        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<Integer, Boolean>();
        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_LR, true);
        overlappingEnablePair.put(BaseDanmaku.TYPE_FIX_BOTTOM, true);
        mContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_STROKEN, 3) //设置描边样式
                .setDuplicateMergingEnabled(false)
                .setScrollSpeedFactor(1.2f) //是否启用合并重复弹幕
                .setScaleTextSize(1.2f) //设置弹幕滚动速度系数,只对滚动弹幕有效
                .setCacheStuffer(new SpannedCacheStuffer(), mCacheStufferAdapter)
                .setMaximumLines(maxLinesPair) //设置最大显示行数
                .preventOverlapping(overlappingEnablePair); //设置防弹幕重叠，null为允许重叠

        if (mDanmakuView != null) {
            mParser = createParser(this.getResources().openRawResource(R.raw.comments)); //创建解析器对象，从raw资源目录下解析comments.xml文本
            mDanmakuView.setCallback(new master.flame.danmaku.controller.DrawHandler.Callback() {
                @Override
                public void updateTimer(DanmakuTimer timer) {
                }

                @Override
                public void drawingFinished() {

                }

                @Override
                public void danmakuShown(BaseDanmaku danmaku) {
                }

                @Override
                public void prepared() {
                    mDanmakuView.start();
                }
            });

            mDanmakuView.prepare(mParser, mContext);
            mDanmakuView.showFPS(false); //是否显示FPS
            mDanmakuView.enableDanmakuDrawingCache(true);
        }

        mDanmakuView.hide();
        mDanmakuView.show();
        //暂停
        if (mDanmakuView != null && mDanmakuView.isPrepared()) {
            mDanmakuView.pause();
        }
        //继续
        if (mDanmakuView != null && mDanmakuView.isPrepared() && mDanmakuView.isPaused()) {
            mDanmakuView.resume();
        }
    }

    //设置监听器
    private void initOther() {
        if (radioButtonVideoViewGuanzhu.isChecked()) {
            textViewVideoViewGuanzhu.setText("已关注");
        } else {
            textViewVideoViewGuanzhu.setText("关注");
        }

    }

    //初始化数据
    private void initData() {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        uid = extras.getString("url");
        presenter = new VdeoViewPresenter(this);
        presenter.getVideoViewBean(uid);
        //点击之后切换横屏
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_portrait);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    //成功的方法
    @Override
    public void getVideoViewSuccess(ZhiBoBean zhiBoBean) {

        //设置视频地址,并且可以自动匹配清晰度
        if (zhiBoBean.getLive().getWs().getFlv().getSan() != null) {
            url = zhiBoBean.getLive().getWs().getFlv().getSan().getSrc();
        } else if (zhiBoBean.getLive().getWs().getFlv().getSi() != null) {
            url = zhiBoBean.getLive().getWs().getFlv().getSi().getSrc();
        } else if (zhiBoBean.getLive().getWs().getFlv().getWu() != null) {
            url = zhiBoBean.getLive().getWs().getFlv().getWu().getSrc();
        } else if (zhiBoBean.getLive().getWs().getHls().getSan() != null) {
            url = zhiBoBean.getLive().getWs().getHls().getSan().getSrc();
        } else if (zhiBoBean.getLive().getWs().getHls().getSi() != null) {
            url = zhiBoBean.getLive().getWs().getHls().getSi().getSrc();
        } else if (zhiBoBean.getLive().getWs().getHls().getWu() != null) {
            url = zhiBoBean.getLive().getWs().getHls().getWu().getSrc();
        } else if (zhiBoBean.getRoomLines().get(0).getHls().getSan() != null) {
            url = zhiBoBean.getRoomLines().get(0).getHls().getSan().getSrc();
        } else if (zhiBoBean.getRoomLines().get(0).getHls().getSi() != null) {
            url = zhiBoBean.getRoomLines().get(0).getHls().getSi().getSrc();
        } else if (zhiBoBean.getRoomLines().get(0).getHls().getWu() != null) {
            url = zhiBoBean.getRoomLines().get(0).getHls().getWu().getSrc();
        } else if (zhiBoBean.getRoomLines().get(0).getFlv().getSan() != null) {
            url = zhiBoBean.getRoomLines().get(0).getFlv().getSan().getSrc();
        } else if (zhiBoBean.getRoomLines().get(0).getFlv().getSi() != null) {
            url = zhiBoBean.getRoomLines().get(0).getFlv().getSi().getSrc();
        } else if (zhiBoBean.getRoomLines().get(0).getFlv().getWu() != null) {
            url = zhiBoBean.getRoomLines().get(0).getFlv().getWu().getSrc();
        }
        if (url != null) {
            videoView_videoPlay.setVideoURI(Uri.parse(url));
        }
        //设置头像
        Glide.with(context).load(zhiBoBean.getAvatar())
                .transform(new GlideRoundTransform(context,90)).into(imageViewViewViewTouxiang);
        //设置介绍
        textViewVideoViewName.setText(zhiBoBean.getNick());
        textViewVideoViewJieshao.setText(zhiBoBean.getTitle());
        //点击进入全屏模式
        imageViewViewViewFull.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置全屏模式
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                //让半屏的布局小时
                relativeLayoutVideoViewVertical2.setVisibility(View.GONE);
                relativeLayoutVideoViewVertical1.setVisibility(View.GONE);
                //将VideoView设置为全屏
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.FILL_PARENT,
                        RelativeLayout.LayoutParams.FILL_PARENT);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                videoView_videoPlay.setLayoutParams(layoutParams);
            }
        });

        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            //让半屏的布局小时
            relativeLayoutVideoViewVertical2.setVisibility(View.GONE);
            relativeLayoutVideoViewVertical1.setVisibility(View.GONE);
        }

        //设置控制器
        controller = new MediaController(context);
        //控制器绑定VideoView
        controller.setMediaPlayer(videoView_videoPlay);
        //获得焦点
        videoView_videoPlay.requestFocus();
        //开始播放
        videoView_videoPlay.start();
        //初始化手势对象
        gesture = new GestureDetectorCompat(context, new MyGestureDetectorCompat());
        //初始化音频管理器
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        //获取系统最大声
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //去掉seekBar
        controller.setVisibility(View.GONE);
        //给videoView_videoPlay设置controller
        videoView_videoPlay.setMediaController(controller);
    }

    @Override
    public void getVideoViewFail(String error) {
        ToastUtils.showToast(context, error);
    }

    //识别手势操作的内部类,这个方法至关重要
    class MyGestureDetectorCompat extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                //获取坐标点
                float mOldX = e1.getX(), mOldY = e1.getY();
                int y = (int) e2.getRawY();
                //窗口管理器
                Display disp = getWindowManager().getDefaultDisplay();
                //获得屏幕宽高
                int windowWidth = disp.getWidth();
                int windowHeight = disp.getHeight();
                //经过计算判断是否滑动的是右边
                if (mOldX > windowWidth * 4.0 / 5) {
                    //将滑动距离带进调节音量的方法中
                    onVolumeSlide((mOldY - y) / windowWidth);
                    //经过计算判断是否滑动的是左边
                } else if (mOldX < windowWidth / 5) {
                    //将滑动距离带进调节亮度的方法中
                    onBrightnessSlide((mOldY - y) / windowHeight);
                }
                return super.onScroll(e1, e2, distanceX, distanceY);
            }
            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //判断我们的手势识别类是否进行了识别操作
        //操作了返回true，没操作默认
        if (gesture.onTouchEvent(event) && getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            //return true 是因为手机太敏感，我只让响应一次
            return true;
        }
        customVolume = -1;
        mBrightness = -1f;
        return super.onTouchEvent(event);
    }

    //改变音量
    private void onVolumeSlide(float percent) {
        //判断当前音量是否是-1，是则没有获取当前系统音量
        if (customVolume == -1) {
            //获得系统当前音量
            customVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            //判断当前音量是否为负数，是则设置最小为0
            if (customVolume < 0) {
                //如果当前音量小于0则给变量赋最小的值0
                customVolume = 0;
            }
        }
        //计算用户滑动的距离
        int index = (int) ((percent * maxVolume) + customVolume);
        //判断该距离是否大于最大音量值，是则把给变量赋值为最大值，否则最小值
        if (index > maxVolume) {
            index = maxVolume;
        } else if (index < 0) {
            index = 0;
        }
        //设置音量
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
    }

    //滑动改变亮度
    private void onBrightnessSlide(float percent) {
        if (mBrightness < 0) {
            //获得屏幕亮度
            mBrightness = getWindow().getAttributes().screenBrightness;
            //判断当前亮度是否小于0.01f，是的话则给变量赋值0.01f放置屏幕变黑
            if (mBrightness <= 0.01f)
                mBrightness = 0.01f;

        }
        /**WindowManager.LayoutParams 是 WindowManager 接口的嵌套类；
         它继承于 ViewGroup.LayoutParams； 它用于向WindowManager描述Window的管理策略。**/
        //获取window窗口属性
        WindowManager.LayoutParams lpa = getWindow().getAttributes();
        //将当前屏幕亮度加上我们移动的距离的值赋给lpa（窗口管理）
        lpa.screenBrightness = mBrightness + percent;
        //判断当前亮度是否大于1，是则设置为1,（亮度最大只能是1）
        if (lpa.screenBrightness > 1.0f)
            lpa.screenBrightness = 1.0f;
            //判断是否小于0.01，防止黑屏最小设置成0.01
        else if (lpa.screenBrightness < 0.01f)
            lpa.screenBrightness = 0.01f;
        //让设置好的亮度生效
        getWindow().setAttributes(lpa);
    }

    //重写返回事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                relativeLayoutVideoViewVertical2.setVisibility(View.VISIBLE);
                relativeLayoutVideoViewVertical1.setVisibility(View.VISIBLE);
                //设置半屏
                RelativeLayout.LayoutParams lp=new  RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                        600);
                videoView_videoPlay.setLayoutParams(lp);
                return false;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //////////////////////////////////////////////////////////////////////////////
    //开始进行弹幕

    /**
     * 创建解析器对象，解析输入流
     *
     * @param stream
     * @return
     */
    private BaseDanmakuParser createParser(InputStream stream) {

        if (stream == null) {
            return new BaseDanmakuParser() {

                @Override
                protected Danmakus parse() {
                    return new Danmakus();
                }
            };
        }
        ILoader loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI);

        try {
            loader.load(stream);
        } catch (IllegalDataException e) {
            e.printStackTrace();
        }
        BaseDanmakuParser parser = new BiliDanmukuParser();
        IDataSource<?> dataSource = loader.getDataSource();
        parser.load(dataSource);
        return parser;
    }

    private static class BackgroundCacheStuffer extends SpannedCacheStuffer {
        // 通过扩展SimpleTextCacheStuffer或SpannedCacheStuffer个性化你的弹幕样式
        final Paint paint = new Paint();

        @Override
        public void measure(BaseDanmaku danmaku, TextPaint paint, boolean fromWorkerThread) {
            danmaku.padding = 10;  // 在背景绘制模式下增加padding
            super.measure(danmaku, paint, fromWorkerThread);
        }

        @Override
        public void drawBackground(BaseDanmaku danmaku, Canvas canvas, float left, float top) {
            paint.setColor(0x8125309b);  //弹幕背景颜色
            canvas.drawRect(left + 2, top + 2, left + danmaku.paintWidth - 2, top + danmaku.paintHeight - 2, paint);
        }


        @Override
        public void drawStroke(BaseDanmaku danmaku, String lineText, Canvas canvas, float left, float top, Paint paint) {
            // 禁用描边绘制
        }
    }

    private void addDanmaku(boolean islive) {
        BaseDanmaku danmaku = mContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        if (danmaku == null || mDanmakuView == null) {
            return;
        }

        danmaku.text = "这是一条弹幕" + System.nanoTime();
        danmaku.padding = 5;
        danmaku.priority = 0;  //0 表示可能会被各种过滤器过滤并隐藏显示 //1 表示一定会显示, 一般用于本机发送的弹幕
        danmaku.isLive = islive; //是否是直播弹幕
        danmaku.time = mDanmakuView.getCurrentTime() + 1200; //显示时间
        danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f);
        danmaku.textColor = Color.RED;
        danmaku.textShadowColor = Color.WHITE; //阴影/描边颜色
        danmaku.borderColor = Color.GREEN; //边框颜色，0表示无边框
        mDanmakuView.addDanmaku(danmaku);

    }

    private void addDanmaKuShowTextAndImage(boolean islive) {
        BaseDanmaku danmaku = mContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
        drawable.setBounds(0, 0, 100, 100);
        SpannableStringBuilder spannable = createSpannable(drawable);
        danmaku.text = spannable;
        danmaku.padding = 5;
        danmaku.priority = 1;  // 一定会显示, 一般用于本机发送的弹幕
        danmaku.isLive = islive;
        danmaku.time = mDanmakuView.getCurrentTime() + 1200;
        danmaku.textSize = 25f * (mParser.getDisplayer().getDensity() - 0.6f);
        danmaku.textColor = Color.RED;
        danmaku.textShadowColor = 0; // 重要：如果有图文混排，最好不要设置描边(设textShadowColor=0)，否则会进行两次复杂的绘制导致运行效率降低
        danmaku.underlineColor = Color.GREEN;
        mDanmakuView.addDanmaku(danmaku);
    }

    /**
     * 创建图文混排模式
     *
     * @param drawable
     * @return
     */
    private SpannableStringBuilder createSpannable(Drawable drawable) {
        String text = "bitmap";
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
        ImageSpan span = new ImageSpan(drawable);//ImageSpan.ALIGN_BOTTOM);
        spannableStringBuilder.setSpan(span, 0, text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.append("图文混排");
        spannableStringBuilder.setSpan(new BackgroundColorSpan(Color.parseColor("#8A2233B1")), 0, spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return spannableStringBuilder;
    }

    private BaseCacheStuffer.Proxy mCacheStufferAdapter = new BaseCacheStuffer.Proxy() {

        private Drawable mDrawable;

        /**
         * 在弹幕显示前使用新的text,使用新的text
         * @param danmaku
         * @param fromWorkerThread 是否在工作(非UI)线程,在true的情况下可以做一些耗时操作(例如更新Span的drawblae或者其他IO操作)
         * @return 如果不需重置，直接返回danmaku.text
         */
        @Override
        public void prepareDrawing(final BaseDanmaku danmaku, boolean fromWorkerThread) {
            if (danmaku.text instanceof Spanned) { // 根据你的条件检查是否需要需要更新弹幕
                // FIXME 这里只是简单启个线程来加载远程url图片，请使用你自己的异步线程池，最好加上你的缓存池
                new Thread() {

                    @Override
                    public void run() {
                        String url = "http://www.bilibili.com/favicon.ico";
                        InputStream inputStream = null;
                        Drawable drawable = mDrawable;
                        if (drawable == null) {
                            try {
                                URLConnection urlConnection = new URL(url).openConnection();
                                inputStream = urlConnection.getInputStream();
                                drawable = BitmapDrawable.createFromStream(inputStream, "bitmap");
                                mDrawable = drawable;
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            } finally {
                                IOUtils.closeQuietly(inputStream);
                            }
                        }
                        if (drawable != null) {
                            drawable.setBounds(0, 0, 100, 100);
                            SpannableStringBuilder spannable = createSpannable(drawable);
                            danmaku.text = spannable;
                            if (mDanmakuView != null) {
                                mDanmakuView.invalidateDanmaku(danmaku, false);
                            }
                            return;
                        }
                    }
                }.start();
            }
        }

        @Override
        public void releaseResource(BaseDanmaku danmaku) {
            // TODO 重要:清理含有ImageSpan的text中的一些占用内存的资源 例如drawable
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind.unbind();
        if (mDanmakuView != null) {
            mDanmakuView.release();
            mDanmakuView = null;
        }
    }
}
